package com.mlog.njyjy.ndop.monitor.service;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.mlog.njyjy.ndop.monitor.dao.entity.TblMsgDictItem;
import com.mlog.njyjy.ndop.monitor.dao.entity.TblProcessBizItem;
import com.mlog.njyjy.ndop.monitor.dao.entity.TblProcessFlowGroup;
import com.mlog.njyjy.ndop.monitor.dao.entity.TblProcessFlowNodeRef;
import com.mlog.njyjy.ndop.monitor.dao.entity.TblProcessMessageCollectItem;
import com.mlog.njyjy.ndop.monitor.dao.entity.TblProcessNode;
import com.mlog.njyjy.ndop.monitor.dao.entity.TblSysContactPerson;
import com.mlog.njyjy.ndop.monitor.dao.service.impl.TblMsgDictItemServiceImpl;
import com.mlog.njyjy.ndop.monitor.dao.service.impl.TblProcessBizItemServiceImpl;
import com.mlog.njyjy.ndop.monitor.dao.service.impl.TblProcessFlowGroupServiceImpl;
import com.mlog.njyjy.ndop.monitor.dao.service.impl.TblProcessFlowNodeRefServiceImpl;
import com.mlog.njyjy.ndop.monitor.dao.service.impl.TblProcessMessageCollectItemServiceImpl;
import com.mlog.njyjy.ndop.monitor.dao.service.impl.TblProcessNodeServiceImpl;
import com.mlog.njyjy.ndop.monitor.dao.service.impl.TblSysContactPersonServiceImpl;
import com.mlog.njyjy.ndop.monitor.pojo.MessageDO;
import com.mlog.njyjy.ndop.monitor.pojo.Option;
import com.mlog.njyjy.ndop.monitor.pojo.ProcessGroup;
import com.mlog.njyjy.ndop.monitor.pojo.ProcessNode;
import com.mlog.njyjy.ndop.monitor.pojo.ProcessVO;
import com.mlog.njyjy.ndop.monitor.pojo.ProductVO;
import com.mlog.njyjy.ndop.monitor.redis.MessageClient;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;

@Service
public class ProductMonitorService {

	@Autowired
	private TblMsgDictItemServiceImpl dictItemServ;

	@Autowired
	private TblProcessFlowGroupServiceImpl groupServ;

	@Autowired
	private TblSysContactPersonServiceImpl userServ;

	@Autowired
	private TblProcessFlowNodeRefServiceImpl processServ;

	@Autowired
	private TblProcessNodeServiceImpl nodeServ;

	@Autowired
	private TblProcessBizItemServiceImpl itemServ;

	@Autowired
	private TblProcessMessageCollectItemServiceImpl msgServ;

	@Autowired
	private MessageClient client;

	public JSONObject listProduct(String startTime, String endTime, String keyWord, String alarmState, int pageNo,
			int pageCount) {
		int pageIndex = (pageNo - 1) * pageCount;
		String startDay = startTime.substring(0, 8);
		String endDay = endTime.substring(0, 8);
		List<String> msgIndices = client.get_list_msg("0_" + startDay);
		if (!startDay.equals(endDay))
			msgIndices.addAll(client.get_list_msg("0_" + endDay));
		List<ProductVO> viewobjs = new ArrayList<>();
		List<ProductVO> pageobjs = new ArrayList<>();
		for (String key : msgIndices) {
			MessageDO msg = client.getMsg(key);
			if (msg == null)
				continue;
			ProductVO bean = new ProductVO();
			bean.setDataTime(msg.getDatetime());
			bean.setFileName(msg.getFileNames());
			bean.setId(msg.getID());
			bean.setProductLine(msg.getPID());
			if (!StrUtil.isEmpty(keyWord) && !msg.getBody().contains(keyWord))
				continue;
			bean.setSystem(msg.getSource());
			bean.setAlarmState("0");
			viewobjs.add(bean);
			if (pageobjs.size() == pageCount)
				break;
			if (viewobjs.size() >= pageIndex)
				pageobjs.add(bean);
		}
		JSONObject ret = new JSONObject();
		ret.put("list", pageobjs);
		ret.put("total", msgIndices.size());
		ret.put("title", DateUtil.format(new Date(), "yyyy/MM/dd HH:mm:ss 更新"));
		return ret;
	}

	public Object listProcessCategory() {
		Map<String, List<ProcessGroup>> ret = new HashMap<>();
		List<ProcessGroup> groups = new ArrayList<>();
		List<TblProcessFlowGroup> parents = groupServ.list(new QueryWrapper<TblProcessFlowGroup>().eq("parent_id", 0));
		for (TblProcessFlowGroup parent : parents) {
			ProcessGroup group = new ProcessGroup();
			group.setId(parent.getId());
			group.setName(parent.getAliName());
			recursionGroups(group);
			groups.add(group);
		}
		ret.put("process", groups);
		return ret;
	}

	void recursionGroups(ProcessGroup parentGroup) {
		Long pid = parentGroup.getId();
		List<TblProcessFlowGroup> sons = groupServ.list(new QueryWrapper<TblProcessFlowGroup>().eq("parent_id", pid));
		if (sons != null && sons.size() > 0) {
			for (TblProcessFlowGroup son : sons) {
				ProcessGroup sonGroup = new ProcessGroup();
				sonGroup.setId(son.getId());
				sonGroup.setName(son.getAliName());
				if (parentGroup.getProcess() == null)
					parentGroup.setProcess(new ArrayList<>());
				parentGroup.getProcess().add(sonGroup);
				recursionGroups(sonGroup);
			}
		}
	}

	public Object listProcessView(long id, String date, String name, String pid, Boolean alarm) {
		if (StrUtil.isEmpty(date))
			date = DateUtil.format(new Date(), "yyyyMMdd");
	
		TblProcessFlowGroup process = groupServ.getById(id);
		if (process == null)
			return null;
		List<TblProcessFlowNodeRef> nodeRefs = processServ
				.list(new QueryWrapper<TblProcessFlowNodeRef>().eq("flow_group_id", id).orderByAsc("sequence"));
		if(nodeRefs.isEmpty())
			return null;
		TblProcessFlowNodeRef nodeRef0 = nodeRefs.get(0);
		List<TblProcessBizItem> items = itemServ
				.list(new QueryWrapper<TblProcessBizItem>().eq("node_id", nodeRef0.getNodeId()));
		Map<String, List<ProcessVO>> ret = new HashMap<>();
		List<ProcessVO> views = new ArrayList<>();
		int index = 1;
		for (TblProcessBizItem item : items) {
			String startForetime = StrUtil.padPre(item.getStartForecastTime().split(":")[0], 4, '0');
			int interval = item.getInterval();
			int startAge = item.getStartAge();
			int validtime = item.getValidTime();
			int periodNum = (validtime - startAge) / interval + 1;
			for (int i = 1; i <= periodNum; i++) {
				long t1 = System.currentTimeMillis();
				int reportAge = startAge + (i - 1) * interval;
				String period = StrUtil.padPre(String.valueOf(reportAge), 4, "0");
				List<ProcessNode> pnodes = new ArrayList<>();
				ProcessVO vo = new ProcessVO();

				for (TblProcessFlowNodeRef nodeRef : nodeRefs) {
					TblProcessNode processNode = nodeServ.getById(nodeRef.getNodeId());
					String collectway = processNode.getCollectWay();
					ProcessNode node = new ProcessNode();
					node.setName(processNode.getName());
					if ("message".equalsIgnoreCase(collectway)) {
						TblProcessMessageCollectItem collectitem = msgServ.getOne(
								new QueryWrapper<TblProcessMessageCollectItem>().eq("node_id", nodeRef.getNodeId()));
						if (collectitem != null) {
							node.setSource(collectitem.getSource());
							String rediskey1 = String.format("%s_%s%s_%s_%s", collectitem.getTopic(),
									collectitem.getType(), startForetime + period + period, collectitem.getSource(),
									date);
							System.out.println(rediskey1);
							List<MessageDO> msgs = client.getMsgList(rediskey1);
							if (msgs.size() > 0) {
								node.setClickable(true);
								node.setMessage(msgs.get(0));
								node.setStatus(1);
							}
						}
					}
					pnodes.add(node);
				}
				vo.setId(index++);
				vo.setName(String.format("%s_%s起报_%s时效", process.getName(), startForetime.substring(2), reportAge));
				vo.setNode(pnodes);
				vo.setStatus(0);
				views.add(vo);
				System.out.println("t1:" + (System.currentTimeMillis() - t1));
			}
			
		}
		ret.put("process", views);
		return ret;
	}

	
	public Option getOptions() {
		Option opt = new Option();
		List<TblMsgDictItem> dicts = dictItemServ.list();
		List<TblSysContactPerson> users = userServ.list();
		opt.setContact(users);
		for (TblMsgDictItem dict : dicts) {
			if (dict.getDictId() == 1)
				opt.getTopic().add(dict);
			if (dict.getDictId() == 2)
				opt.getSource().add(dict);
			if (dict.getDictId() == 3)
				opt.getType().add(dict);
		}
		return opt;
	}

}
